/**
 * Created by yang on 2016/12/25.
 */
globelTempId="";
function m$y(obool,newMaskClassName) {
    this.scroll = function (fn) {
        window.onscroll=function () {
            var wScrollY = window.scrollY; // 当前滚动条位置
            var wInnerH = window.innerHeight; // 设备窗口的高度（不会变）
            var bScrollH = document.body.scrollHeight; // 滚动条总高度
            if (wScrollY + wInnerH >= bScrollH){
                if(typeof fn === 'function'){
                    fn()
                }
            }
        }
    };
        this.template=function (obj) {

        var temp_h=document.documentElement.clientHeight;
        var temp_w=document.documentElement.clientWidth;
        var newNode=document.createElement('div');
        newNode.id='templateWarp';
        var thisValue=(obj.val?obj.val:'<img src="" ' +
        'style="height: 0.5rem; vertical-align: middle;">');
        newNode.innerHTML="<div style='display: inline-block;  color: white;  padding: 0.2rem 0.14rem; font-size: 0.28rem;text-align: center;" +
            " background:rgba(0,0,0,0.71);  border-radius:0.1rem;max-width:40%;min-width: 1.46rem;" +
            " position: absolute;  left: 50%;  top: 50%; box-sizing: border-box; transform:translate(-50%,-50%);  " +
            "-webkit-transform:translate(-50%,-50%);  -o-transform:translate(-50%,-50%);  -moz-transform:translate(-50%,-50%);  " +
            "-ms-transform:translate(-50%,-50%);'>" +
            thisValue+
            "</div>"
        newNode.style.cssText="height:"+temp_h+"px;width:"+temp_w+"px;top:0;left:0;position: fixed;z-index:9999999999999;";
        var thisBody=document.body;
        if(!document.getElementById('templateWarp')){
            thisBody.appendChild(newNode);
        }
        else {
            var ooojj=document.querySelectorAll('#templateWarp>div')[0];
            ooojj.innerHTML=thisValue;
            clearTimeout(globelTempId)
        }

        if(('time' in obj)&& (typeof obj.time== 'number')){

            globelTempId=window.setTimeout(function () {
                      var willRemoveNode=document.getElementById('templateWarp');
                      thisBody.removeChild(willRemoveNode);
                if(('fn' in obj)&& (typeof obj.fn== 'function')){
                    obj.fn()
                }
                  },obj.time)
        }

    };
        this.hiddenScroll=function (oval) {
          window.scrollTo(0,0)
          var temp_h1 = document.body.clientHeight;
          var temp_h2 = document.documentElement.clientHeight;

          var isXhtml = (temp_h2 <= temp_h1 && temp_h2 != 0) ? true : false;
          var htmlbody = isXhtml ? document.documentElement : document.body;
          if (oval===false) {
            htmlbody.style.overflow = "auto";
          } else if(oval===true) {
            htmlbody.style.overflow = "hidden";
          }
            else if(oval&&typeof oval=='string'){
              this.dom(oval)[0].style.height=document.documentElement.clientHeight+'px'
            }
            return  htmlbody.clientHeight;

        };
        this.sessionStores=(function () {
                return{
                    get:function (okey) {
                        if(typeof okey=="object"){
                            throw "参数不能是对象"
                            return
                        }
                        //var ooval=baseCode.decode(window.sessionStorage.getItem(okey))
                        var ooval=(window.sessionStorage.getItem(okey))
                        try {
                            ooval=JSON.parse(ooval)
                        }
                        catch(m){

                        }
                        return ooval
                    },
                    set:function (okey,obj) {
                        if(!okey){
                            throw "键名参数异常"
                            return
                        }
                        if(typeof obj=='object'){
                            obj=JSON.stringify(obj)
                        }
                        else if(obj==null){
                            obj=""
                        }
                        // obj=baseCode.encode(obj)
                        window.sessionStorage.setItem(okey+'',obj)
                    },
                    remove:function (arr) {
                        if(typeof arr =='string'){
                            window.sessionStorage.removeItem(arr)
                        }
                        else if(Object.prototype.toString.call(arr) === '[object Array]'){
                            for(var ini=0;ini<arr.length;ini++){
                                window.sessionStorage.removeItem(arr[ini])
                            }
                        }
                        else if(typeof arr=='undefined'||arr==null){
                            window.sessionStorage.clear();
                        }
                        else {
                            throw "参数异常"
                        }
                    }
                }})();
        this.cookies=(function () {
        return{
            set:function (oname,ovalue,otime)
            {
                if(typeof otime!='number'){
                    otime=30*24
                }
                var exp = new Date();
                exp.setTime(exp.getTime() + otime*60*60*1000);
                if(!oname){
                    throw "键名参数异常"
                    return
                }
                if(typeof ovalue=='object'){
                    ovalue=JSON.stringify(ovalue)
                }
                else if(ovalue==null){
                    ovalue=""
                }
                document.cookie = oname + "="+ escape (ovalue) + ";expires=" + exp.toGMTString();
            }
            ,

//读取cookies
            get:function (oname)
            {
                if(typeof oname=="object"){
                    throw "参数不能是对象"
                    return
                }
                if (document.cookie.length>0)
                {
                    c_start=document.cookie.indexOf(oname + "=")
                    if (c_start!=-1)
                    {
                        c_start=c_start + oname.length+1
                        c_end=document.cookie.indexOf(";",c_start)
                        if (c_end==-1) c_end=document.cookie.length
                        var getValue=unescape(document.cookie.substring(c_start,c_end))
                        try {
                            getValue=JSON.parse(getValue)
                        }
                        catch(m){

                        }

                        return getValue
                    }
                }
                return false
            }
            ,
//删除cookies
            remove: function (oname)
            {
                var exp = new Date();
                exp.setTime(exp.getTime() - 10);
                if(typeof oname =='string'){
                    var cval=this.get(oname);
                    if(cval!=false&&cval!=null)
                    {document.cookie= oname + "="+cval+";expires="+exp.toGMTString();}
                }
                else if(Object.prototype.toString.call(oname) === '[object Array]'){
                    for(var ini=0;ini<oname.length;ini++){
                        var cval=this.get(oname[ini]);
                        if(cval!=false&&cval!=null)
                        {document.cookie= oname[ini] + "="+cval+";expires="+exp.toGMTString();}
                    }
                }
                else {
                    throw "参数异常"
                }

            }
        }
    })();
        this.localStrages=(function () {
            return{
                get:function (okey) {
                    if(typeof okey=="object"){
                        throw "参数不能是对象"
                        return
                    }
                   // var ooval=baseCode.decode(window.localStorage.getItem(okey+''))
                    var ooval=window.localStorage.getItem(okey+'')
                    try {
                        ooval=JSON.parse(ooval)
                    }
                    catch(m){

                    }

                    return ooval
                },
                set:function (okey,obj) {
                    if(!okey){
                        throw "键名参数异常"
                        return
                    }
                    if(typeof obj=='object'){
                        obj=JSON.stringify(obj)
                    }
                    else if(obj==null){
                        obj=""
                    }
                    //obj=baseCode.encode(obj)
                    window.localStorage.setItem(okey+'',obj)
                },
                remove:function (arr) {
                    if(typeof arr =='string'){
                        window.localStorage.removeItem(arr)
                    }
                    else if(Object.prototype.toString.call(arr) === '[object Array]'){
                        for(var ini=0;ini<arr.length;ini++){
                            window.localStorage.removeItem(arr[ini])
                        }
                    }
                    else if(typeof arr=='undefined'||arr==null){
                        window.localStorage.clear();
                    }
                    else {
                        throw "参数异常"
                    }
                }
            }
        })();
        this.resizes=function (fonts,initW,minW) {
          var myIndoc=window.document.documentElement;
          var myIndocWidth=window.document.documentElement.clientWidth ;
          if(minW&&myIndocWidth<=minW){myIndocWidth=min};
          var myInft=fonts*myIndocWidth/initW;
          myIndoc.style.fontSize=myInft+'px';
            this.rem=myInft;
            this.precent=myIndocWidth/initW
          return  {rem:myInft, percent:myIndocWidth/initW};
      };
        this.filters=function (filtersType) {
             if(filtersType==='number'){
                 return function (oval) {
                     var newNumArry=ovalue.split("");
                     var newNum=[];
                     for (var oi=0;oi<newNumArry.length;oi++){
                         if((newNumArry.length-oi)%3==0&&oi!=0){

                             newNum.push(',');
                             newNum.push(newNumArry[oi]);
                         }
                         else {
                             newNum.push(newNumArry[oi])
                         }
                     }
                     return newNum.join("")

                 }
             }
         };
         this.each=function (oarry,fn) {
             if(Object.prototype.toString.call(arr) != '[object Array]'){
                 throw "参数不是数组"
                 return
             }
             for (var my=0;my<oarry;my++){
                 oarry[my]["templateFn"]=function () {

                 }
             }
         };
        this.dom=function (t) {
            var mynodes=document.querySelectorAll(t);
          if(mynodes&&mynodes.length>=1){
              mynodes["bind"]=function (obj) {
                mynodes.forEach(function (oitem,oindex) {
                 for(var key in obj){
                   oitem.addEventListener(key,obj[key],true);
                 }
              })
              };
            mynodes["unbind"]=function (obj) {
              mynodes.forEach(function (oitem,oindex) {
                for(var key in obj){
                  oitem.removeEventListener(key,obj[key],true);
                }
              })
            };
              //   this.getBoundingClientRect();
          }
             return mynodes
         };
         this.imgRead=function (resultPath,obj,fn) {
           var base64img = new Image();
           base64img.src = resultPath;
           base64img.crossOrigin="*";
           base64img.crossOrigin = "Anonymous";
           // var type='image/jpeg'
           // if(image/png){
           //
           // }
           // var type=resultPath.split(';')[0].split(':');
           base64img.onload = function(){

             var that = this;
             // 默认按比例压缩
             var w = that.width,
               h = that.height,
               scale = w / h;
             w = obj.width || w;
             h = obj.height || (w / scale);
             var quality = 0.5;// 默认图片质量为1
             //生成canvas
             var canvas = document.createElement('canvas');
             var ctx = canvas.getContext('2d');
             // 创建属性节点
             if(obj.quality && obj.quality <= 1 && obj.quality > 0){
               quality = obj.quality;
             }
             canvas.setAttribute('width',w);
             canvas.setAttribute('height',h);
             ctx.drawImage(that, 0, 0, w, h);
             // 图像质量

             // quality值越小，所绘制出的图像越模糊
             var base64 = canvas.toDataURL('image/jpeg',quality);

             // 回调函数返回base64的值
             if(fn&&typeof fn=='function'){
               console.log(base64)
               fn(base64);
             }

           }
         }
         this.dealImage=function(obool,files, obj,fn){
           var myReader = new FileReader();
           myReader.onload = function (e){
             var resultPath = e.target.result;
             if (!resultPath){
               return;
             }
             if(resultPath.indexOf('jpg')!=-1||resultPath.indexOf('png')!=-1|| resultPath.indexOf('JPG')!=-1||resultPath.indexOf('PNG')!=-1||resultPath.indexOf('jpeg')!=-1||resultPath.indexOf('JPEG')!=-1){

               if(obool===false){
                 m$.template({
                   val: '',
                   time: 1
                 })
                 fn(resultPath);
               }
              else {
               m$.imgRead(resultPath,obj,fn)
             }
             }
             else {
               if (!resultPath) {
                 m$.template({
                   val: '请选择<br>图片文件',
                   time: 1500
                 })
               }
             }
           };
           myReader.readAsDataURL(files);
  },
           this.documentTitle=function (val) {

             var $iframe = document.createElement('iframe');

             $iframe.src="./static/1.html?"+(new Date()).getTime();
             $iframe.style="display:none;";
             document.title=val;
             console.log($iframe)
             m$.dom('body')[0].appendChild($iframe);
            $iframe.onload=function () {
              window.document.title=val;
              setTimeout(function() {
                window.document.title=val;
                $iframe.onload=null;
                m$.dom('body')[0].removeChild($iframe);
              }, 10);
            }
           }
}
window.m$=new m$y();
console.log(m$)
window.m$.resizes(100,750,window);
var okImgDiv='<div class="okImgDiv">' +
    '<img src="" alt="">' +
    '<p>操作成功</p>' +
    '</div>  ';
var agaen=navigator.userAgent.toLowerCase();
var phoneStatus=false;
if(agaen.indexOf('iphone')>=0){
  phoneStatus=true;
}
